package com.ruoyi.store.service.impl;

import static com.ruoyi.store.results.Result.error;
import static com.ruoyi.store.results.Result.ok;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import com.ruoyi.store.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
//import redis.clients.jedis.Jedis;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.machine.EmpCustomDetailVW;
import com.ruoyi.common.core.domain.store.CustomWithStore;
import com.ruoyi.common.core.domain.store.EmpCustomDetail;
import com.ruoyi.common.core.domain.store.EmpStoreVo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PublicUtil;
import com.ruoyi.store.domain.EmpCustomloginStatistics;
import com.ruoyi.store.domain.dto.UserStatistics;
import com.ruoyi.store.domain.vo.EmpCustomDetailVo;
import com.ruoyi.store.domain.vo.EmpPlayerLoginLog;
import com.ruoyi.store.domain.vo.EmpUserInfoVo;
import com.ruoyi.store.mapper.EmpCustomDetailMapper;
import com.ruoyi.store.mapper.EmpPlayerLoginMapper;
import com.ruoyi.store.results.Result;
import com.ruoyi.store.utils.TimerService;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysOperLogService;
import java.util.Timer;
import java.util.TimerTask;
/**
 * @Author:宋红崇
 * @Date:10:36 2024/1/15
 **/
@Service
public class EmpIEmpCustomDetailServiceImpl extends ServiceImpl<EmpCustomDetailMapper, EmpCustomDetail>
        implements IEmpCustomDetailService {

    @Resource
    private IEmpRechargeLogService rechargeLogService;

    @Resource
    private EmpCustomDetailMapper customDetailMapper;

    @Resource
    private IEmpStoreService empStoreService;
    @Autowired
    private IEmpCustomloginStatisticsService empCustomloginStatisticsService;
    @Autowired
    private ISysOperLogService sysOperLogService;
    
    @Resource
    private IEmpStoreService IEmpStoreService;
	@Resource
	private EmpPlayerLoginMapper playerLoginMapper;
    
    
    //当前在线认识，最大在线人数
    Map<String,Integer> nowLoginCountMap = new HashMap<String, Integer>();
    Map<String,Integer> maxLoginCountMap = new HashMap<String, Integer>();
    
    
    /**
     * 根据用户ID获取用户信息
     *
     * @param customID 用户ID
     * @return Result
     */
    @Override
    public Result getByCustomID(String customID) {
//        System.out.println("前端传回的id"+customID);
//        String opeID = AESUtils.decrypt(customID,"123456789abcdefg");
//        String opeID2 = AESUtils.decrypt(opeID,"123456789abcdefg");
        EmpCustomDetailVo empcustomDetailVo = customDetailMapper.getCustomInfo(customID);
        if (empcustomDetailVo == null || empcustomDetailVo.getCustomID() == null) {
            return error("获取失败,customID不存在"+customID);
        }
        System.out.println(empcustomDetailVo);

        return ok("获取成功", empcustomDetailVo);
    }
//        //构造条件
//        LambdaQueryWrapper<EmpCustomDetail> wrapper = new LambdaQueryWrapper<>();
//
//        //获取数据
//        EmpCustomDetail empCustomDetail = getOne(wrapper
//                .eq(EmpCustomDetail::getCustomID, customID));
//        //bean拷贝
//        EmpCustomDetailVo empcustomDetailVo = CopyUtil.copyObject(empCustomDetail, EmpCustomDetailVo.class);

    @Autowired
    private TimerService timerService;

    /**
     * 登录用户（没有用户自动注册）
     */
    @Override
    @Transactional
    public Result loginCustom(String customID,long deptId) {
    	//先查询是否有用户
        LambdaQueryWrapper<EmpCustomDetail> wrapper = new LambdaQueryWrapper<>();
        //List<EmpCustomDetail> customDetails = list(wrapper.eq(EmpCustomDetail::getCustomID, customID));
        EmpCustomDetailVo vo = customDetailMapper.getCustomInfo(customID);

        EmpCustomDetail empCustomDetail = new EmpCustomDetail();
        if (vo==null) {
            empCustomDetail.setCustomID(customID);
            empCustomDetail.setCoins5G(0L);
            empCustomDetail.setTicket(0);
            String Nickname = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
            empCustomDetail.setNickname("用户" + Nickname);
            empCustomDetail.setAvatar("/2024-12-03/img/defaultAvatar.png");
            //设置已登录
            empCustomDetail.setStatus(1);
            //设置未进行过兑换
            empCustomDetail.setFirstExchange(1);
            
            //设置注册账号的部门
            empCustomDetail.setDept_id(deptId);
            //赋值时间和默认值
            Date date = new Date(System.currentTimeMillis());
            DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = sdf.format(date);
            Timestamp nowTime = Timestamp.valueOf(dateStr);
            empCustomDetail.setCREATED_BY(customID);
            empCustomDetail.setCREATED_TIME(nowTime);
            if (!save(empCustomDetail)) {
                return error("登陆失败");
            }

           return ok("登陆成功", empCustomDetail);
        } else {
            vo.setStatus(1);
            //赋值时间和默认值
            vo.setUpdateBy(customID);
            vo.setUpdateTime(new Date());
            if (customDetailMapper.updateById(vo)<=0) {
                return error("登陆失败");
            }
        }
        return ok("登陆成功",vo);
    }

    /**
     * 登录用户（没有用户自动注册）
     */
    @Override
    @Transactional
    public AjaxResult loginUser(String customID) {
        //先查询是否有用户
        LambdaQueryWrapper<EmpCustomDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EmpCustomDetail::getCustomID, customID);
        List<EmpCustomDetail> customDetails = list(wrapper
                .eq(EmpCustomDetail::getCustomID, customID));
        EmpCustomDetail empCustomDetail = new EmpCustomDetail();
        if (customDetails.isEmpty()) {
            /**
             * 短信介入进行注册
             * */
            empCustomDetail.setCustomID(customID);
            empCustomDetail.setCoins5G(0L);
            empCustomDetail.setTicket(0);
            empCustomDetail.setHappyTicket(0);
            String Nickname = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
            empCustomDetail.setNickname("用户" + Nickname);
            empCustomDetail.setAvatar("/2024-12-03/img/defaultAvatar.png");
            //设置已登录
            empCustomDetail.setStatus(1);
            //设置未进行过兑换
            empCustomDetail.setFirstExchange(1);
            //赋值时间和默认值
            Date date = new Date(System.currentTimeMillis());
            DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = sdf.format(date);
            Timestamp nowTime = Timestamp.valueOf(dateStr);
            empCustomDetail.setCREATED_BY(customID);
            empCustomDetail.setCREATED_TIME(nowTime);
            empCustomDetail.setRemark("什么都没留下~");
            empCustomDetail.setPhoneNumber("");
            if (save(empCustomDetail)) {
                return AjaxResult.success("注册成功（跳过短信）注册的id"+customID);
            } else {
                return AjaxResult.error("注册失败");
            }
        } else {
            /**
             * 用户存在
             * */
            //验证登录状态
            EmpCustomDetail empCustomDetail_DB = customDetails.get(0);
            if (empCustomDetail_DB.getStatus() == 0) {
                //未登录
                /**
                 * 短信验证码进行登录
                 * */
                //赋值时间和默认值
                Date date = new Date(System.currentTimeMillis());
                DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = sdf.format(date);
                Timestamp nowTime = Timestamp.valueOf(dateStr);
                empCustomDetail_DB.setUPDATED_BY(customID);
                empCustomDetail_DB.setUPDATED_TIME(nowTime);
                empCustomDetail_DB.setStatus(1);
                if (update(empCustomDetail_DB, wrapper)) {
                    return AjaxResult.success("登录成功（跳过短信）");
                }
                return AjaxResult.error("登陆失败");
            } else {
                /**
                 * 解除定时
                 * */
                empCustomDetail_DB.setStatus(1);
                timerService.cancelExistingTask(customID);
                return AjaxResult.success("成功解除定时器，保持登录状态");
            }
        }
    }
    @Autowired
    private EmpPlayerLoginService playerLoginService;
    @Override
    public AjaxResult loginUser(CustomWithStore customWithStore) {
    	String result = "";
        //先查询是否有用户
        LambdaQueryWrapper<EmpCustomDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EmpCustomDetail::getCustomID, customWithStore.getCustomId());
        List<EmpCustomDetail> customDetails = list(wrapper
                .eq(EmpCustomDetail::getCustomID, customWithStore.getCustomId()));
        EmpCustomDetail empCustomDetailNew = new EmpCustomDetail();
        if (customDetails.isEmpty()) {
            /**
             * 短信介入进行注册
             * */
            empCustomDetailNew.setCustomID(customWithStore.getCustomId());
            empCustomDetailNew.setCoins5G(0L);
            empCustomDetailNew.setTicket(0);
            empCustomDetailNew.setHappyTicket(0);
            empCustomDetailNew.setUser_id(customWithStore.getUserId());
            empCustomDetailNew.setDept_id(customWithStore.getDeptId());
            String Nickname = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
            empCustomDetailNew.setNickname("用户" + Nickname);
            empCustomDetailNew.setAvatar("/2024-12-03/img/defaultAvatar.png");
            //设置已登录
            empCustomDetailNew.setStatus(1);
            //设置未进行过兑换
            empCustomDetailNew.setFirstExchange(1);
            //赋值时间和默认值
            Date date = new Date(System.currentTimeMillis());
            DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = sdf.format(date);
            Timestamp nowTime = Timestamp.valueOf(dateStr);
            empCustomDetailNew.setCREATED_BY(customWithStore.getCustomId());
            empCustomDetailNew.setCREATED_TIME(nowTime);
            empCustomDetailNew.setRemark("什么都没留下~");
            empCustomDetailNew.setPhoneNumber("");
            if (save(empCustomDetailNew)) {
            	result = "注册成功（跳过短信）注册的id"+customWithStore.getCustomId();
            } else {
            	result = "注册失败";
            }
        } else {
            /**
             * 用户存在
             * */
            //验证登录状态
            EmpCustomDetail empCustomDetail_DB = customDetails.get(0);
            if (empCustomDetail_DB.getStatus() == 0) {
                //未登录
                /**
                 * 短信验证码进行登录
                 * */
                //赋值时间和默认值
                Date date = new Date(System.currentTimeMillis());
                DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = sdf.format(date);
                Timestamp nowTime = Timestamp.valueOf(dateStr);
                empCustomDetail_DB.setUPDATED_BY(customWithStore.getCustomId());
                empCustomDetail_DB.setUPDATED_TIME(nowTime);
                empCustomDetail_DB.setStatus(1);
                empCustomDetail_DB.setFirstExchange(1);
                //添加登录记录
                EmpCustomDetailVo empCustomDetail = customDetailMapper.getCustomInfo(customWithStore.getCustomId());
                EmpPlayerLoginLog loginLog = new EmpPlayerLoginLog();
                loginLog.setUserId(customWithStore.getUserId());
                loginLog.setDeptId(customWithStore.getDeptId());
                loginLog.setLoginTime(nowTime);
                loginLog.setNickName(empCustomDetail.getNickname());
                loginLog.setCustomId(customWithStore.getCustomId());
                playerLoginService.insertLoginLog(loginLog);
                if (update(empCustomDetail_DB, wrapper)) {
                	result = "登录成功（跳过短信）";
                }
                result = "登陆失败";
            } else {
                /**
                 * 解除定时
                 * */
                empCustomDetail_DB.setStatus(1);
                empCustomDetail_DB.setFirstExchange(1);
                timerService.cancelExistingTask(customWithStore.getCustomId());
                result = "成功解除定时器，保持登录状态";
            }
        }
        //更新当前在线人数
        EmpStoreVo store = empStoreService.findStoreByCustomId(customWithStore.getCustomId());
        if(store !=null) {
        	String key = "#"+store.getId()+"#"+DateUtils.getDate();//避免出现重复
        	System.out.println("EmpIEmpCustomDetailServiceImpl-310-"+key);
        	if(nowLoginCountMap.containsKey(key)) {
        		Integer nowCount = nowLoginCountMap.get(key)+1;
        		Integer maxCount = maxLoginCountMap.get(key);
        		nowLoginCountMap.put(key, nowCount);
        		System.out.println("EmpIEmpCustomDetailServiceImpl-310-"+nowCount+" -- "+maxCount);
        		//判断当前在线人数是否大于当日最大在线人数，如果大，则更新当日最大在线人数，并更新统计表
        		if(nowCount > maxCount) {
        			maxLoginCountMap.put(key, nowCount);
        			//查到门店当前的统计数据，进行修改
        			EmpCustomloginStatistics storeStatic =  empCustomloginStatisticsService.selectStatisticsByStoreIdAndDate(store.getStoreId().intValue());
        			if(storeStatic!=null) {
        				storeStatic.setMaxOnlineUsers(nowCount);
        				empCustomloginStatisticsService.updateEmpCustomloginStatistics(storeStatic);
        			}
        		}
        		
        	}else {
        		nowLoginCountMap.put(key, 1);
        		maxLoginCountMap.put(key, 1);
        		//查到门店当前的统计数据，进行修改
    			EmpCustomloginStatistics storeStatic =  empCustomloginStatisticsService.selectStatisticsByStoreIdAndDate(store.getStoreId().intValue());
    			if(storeStatic!=null) {
    				storeStatic.setMaxOnlineUsers(1);
    				empCustomloginStatisticsService.updateEmpCustomloginStatistics(storeStatic);
    			}
        	}
        	
        	
        }
        
        return AjaxResult.success(result);
        
    }

    @Override
    @DataScope(deptAlias = "cd", userAlias = "cd.user_id")
    public AjaxResult userList(Long pageNum, Long pageSize, Long StoreID) {
        Long offset = (pageNum - 1) * pageSize;
        List<EmpUserInfoVo> list = customDetailMapper.userList(offset, pageSize, StoreID);
        return AjaxResult.success(list);
    }

    /**
     * 玩家图表分析 门店id为null时
     * @return createTime  用户创建时间  customCount  新用户个数
     */
    @Override
    @DataScope(deptAlias = "cd", userAlias = "cd")
    public AjaxResult getCustomDetail() {
        List<EmpUserInfoVo> chartVoList = customDetailMapper.getCustomDetail();
        return AjaxResult.success(chartVoList);
    }

    /**
     * 玩家图表分析
     * @return createTime  用户创建时间  customCount  新用户个数
     */
    @Override
    @DataScope(deptAlias = "cd", userAlias = "cd")
    public AjaxResult getCustomDetailByStoreId(EmpUserInfoVo empUserInfoVo) {
        List<EmpUserInfoVo> chartVoList = customDetailMapper.getCustomDetailByStoreId(empUserInfoVo);
        return AjaxResult.success(chartVoList);
    }

    @Override
    @DataScope(deptAlias = "cd", userAlias = "cd")
    public List<EmpUserInfoVo> selectEmpCustomList(EmpUserInfoVo empUserInfoVo) {
        return customDetailMapper.selectEmpCustomList(empUserInfoVo);
    }

    @Override
    public int kickingPeople(EmpCustomDetailVo empCustomDetailVo) {
        return customDetailMapper.kickingPeople(empCustomDetailVo);
    }

    @Override
    public int changeStatus(EmpCustomDetailVo empCustomDetailVo) {
        return customDetailMapper.changeStatus(empCustomDetailVo);
    }

    @Override
    @DataScope(deptAlias = "cd", userAlias = "cd")
    public List<EmpStoreVo> selectEmpCustomOnlineList(EmpUserInfoVo empUserInfoVo) {
        return customDetailMapper.selectEmpCustomOnlineList(empUserInfoVo);
    }

    @Override
    public void updateUserLoginStatusToNotLoggedIn() {
        customDetailMapper.updateAllUserLoginStatusToNotLoggedIn();
    }

    @Override
//    @DataScope(deptAlias = "cd", userAlias = "cd")
    public List<EmpCustomDetail> getLoggedInUsersToday() {
        return customDetailMapper.getLoggedInUsersToday();
    }

    @Override
//    @DataScope(deptAlias = "cd", userAlias = "cd")
    public List<EmpCustomDetail> getNewUsersToday() {
        return customDetailMapper.getNewUsersToday();
    }

    @Override
    public Integer getOnlineUserCount() {
        return customDetailMapper.getOnlineUserCount();
    }

    @Override
    public Integer getMaxOnlineUsers() {
        return customDetailMapper.getMaxOnlineUsers();
    }

    @Override
    public AjaxResult getusersStatistics(UserStatistics userStatistics) {
        return customDetailMapper.getusersStatistics(userStatistics);
    }

//    @Autowired
//    private UserRepository userRepository;

    /**
     * 检查openid是否存在
     * @param openid
     */
//    @Override
//    @Transactional
//    public void storeOpenId(String openid) {
//        // 检查数据库中是否已存在该openid
//        EmpCustomDetail existingUser = userRepository.findByOpenid(openid);
//        if (existingUser == null) {
//            // 如果不存在，创建新用户并保存openid
//            EmpCustomDetail newUser = new EmpCustomDetail();
//            newUser.setCustomID(openid);
//            userRepository.save(newUser);
//        }
//    }

    /**
     * 获取用户登录状态
     */
    @Override
    public Result getCustomStatus(String customID) {
        LambdaQueryWrapper<EmpCustomDetail> wrapper = new LambdaQueryWrapper<>();
        EmpCustomDetail customDetail = getOne(wrapper.eq(EmpCustomDetail::getCustomID, customID));
        int status = customDetail.getStatus();
        return ok("获取成功", status);
    }
    
    
    /**
     * 获取用户登录状态
     */
    @Override
    public Result getFiveMinutesCustomStatus(String customID) {
        LambdaQueryWrapper<EmpCustomDetail> wrapper = new LambdaQueryWrapper<>();
        EmpCustomDetail customDetail = getOne(wrapper.eq(EmpCustomDetail::getCustomID, customID));
        int status = customDetail.getStatus();
        //如果未登陆或已退出登陆，则查询是否超过5分钟，如果未超过则还算登陆状态返回
        if(status == 0) {
        	SysOperLog operLog = new SysOperLog();
        	operLog.setOperName(customDetail.getNickname());
        	operLog.setOperTime(DateUtils.getMillis(new Date(),-5)); //查询5分钟内是否有操作记录
        	List<SysOperLog> logList = sysOperLogService.selectOperLogList(operLog);
        	if(!PublicUtil.checkEmptyList(logList)) {
        		status = 1;//如果5分钟内有记录，则算登陆状态
        		EmpCustomDetail detail = new EmpCustomDetail();
        		detail.setCustomID(customID);
        		detail.setStatus(1);//改为在线状态
        		updateEmpCustom(detail);
        	}
        }
        return ok("获取成功", status);
    }
    


    /**
     * 退出登录
     */
    @Override
    @Transactional
    public Result exitCustonLogin(String customID) {
        LambdaQueryWrapper<EmpCustomDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EmpCustomDetail::getCustomID, customID);
        EmpCustomDetail customDetail = getOne(wrapper);
        
        //更新当前在线人数
        EmpStoreVo store = empStoreService.findStoreByCustomId(customID);
        if(store !=null ) {
        	String key = "#"+store.getId()+"#"+DateUtils.getDate();//避免出现重复
        	if(nowLoginCountMap.containsKey(key)) {
	        	nowLoginCountMap.put(key, nowLoginCountMap.get(key)-1);
        	}
        }
        //设置未登录
        customDetail.setStatus(0);
        if (!update(customDetail, wrapper)) {
            return error("退出登录失败");
        }
        return ok("退出登录成功");
    }

    /**
     * 查询客户管理列表
     */
//    @Override
//    public Result selectEmpCustomList(EmpCustomDetail empCustom, Long pageNum, Long pageSize) {
//        String customID = empCustom.getCustomID();
//        List<EmpCustomDetail> customDetailList = new LambdaQueryChainWrapper<>(customDetailMapper)
//                .eq(customID != null, EmpCustomDetail::getCustomID, customID)
//                .list();
//        //分页
//        List<EmpCustomDetail> customDetails = customDetailList
//                .stream()
//                .skip((pageNum - 1) * pageSize)
//                .limit(pageSize)
//                .collect(Collectors.toList());
//
//        Map<String, Object> map = new HashMap();
//        map.put("total", customDetailList.size());
//        map.put("list", customDetails);
//
//        return ok("获取成功", map);
//    }
//    @Override
//    public Result selectEmpCustomList(EmpCustomDetail empCustom, Long pageNum, Long pageSize) {
//        try {
//            String encryptedCustomID = empCustom.getCustomID();
//            // 解密 customID
//            String decryptedCustomID = AESUtils.decrypt(encryptedCustomID,"");
//
//            List<EmpCustomDetail> customDetailList = new LambdaQueryChainWrapper<>(customDetailMapper)
//                    .eq(decryptedCustomID != null, EmpCustomDetail::getCustomID, decryptedCustomID)
//                    .list();
//            for (EmpCustomDetail detail : customDetailList) {
//                detail.setDecryptedCustomID(AESUtils.decrypt(detail.getCustomID()));
//            }
//            // 方法的其余部分保持不变...
//            List<EmpCustomDetail> customDetails = customDetailList
//                    .stream()
//                    .skip((pageNum - 1) * pageSize)
//                    .limit(pageSize)
//                    .collect(Collectors.toList());
//
//            Map<String, Object> map = new HashMap<>();
//            map.put("total", customDetailList.size());
//            map.put("list", customDetails);
//
//            return ok("获取成功", map);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return error("解密失败");
//        }
//    }

    /**
     * 获取客户管理详细信息
     */
    @Override
    public EmpCustomDetail selectEmpCustomByID(String id) {
       
    	List<EmpCustomDetail> customList = selectEmpCustomByIDList(id);
    	if(PublicUtil.checkEmptyList(customList)) {
    		return null;
    	}else {
    		return customList.get(0);
    	}
    }
    
    public List<EmpCustomDetail> selectEmpCustomByIDList(String id) {
        return new LambdaQueryChainWrapper<>(customDetailMapper)
                .eq(EmpCustomDetail::getCustomID, id)
                .list();
    }
    

    /**
     * 插入客户管理
     */
    @Override
    public AjaxResult insertEmpCustom(EmpCustomDetail empCustom) {
        return null;
    }

    /**
     * 修改客户管理
     */
    @Override
    public AjaxResult updateEmpCustom(EmpCustomDetail empCustom) {
        String customID = empCustom.getCustomID();
        LambdaQueryWrapper<EmpCustomDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EmpCustomDetail::getCustomID, customID);
        if (!update(empCustom, wrapper)) {
            return AjaxResult.error("修改失败");
        }
        return AjaxResult.success("修改成功");
    }

    /**
     * 删除客户管理
     */
    @Override
    public AjaxResult deleteEmpCustomByIDs(String[] iDs) {
        return null;
    }

    @Override
    public AjaxResult editPersonalInformation(EmpCustomDetailVo customDetailVo) {
        LambdaQueryWrapper<EmpCustomDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EmpCustomDetail::getCustomID, customDetailVo.getCustomID());
        EmpCustomDetail one = getOne(wrapper);
        if (!Objects.equals(customDetailVo.getAvatar(), one.getAvatar())) {
            one.setAvatar(customDetailVo.getAvatar());
        }
        if (!Objects.equals(customDetailVo.getNickname(), one.getNickname())) {
            one.setNickname(customDetailVo.getNickname());
        }
        if (!Objects.equals(customDetailVo.getBirthday(), one.getBirthday())) {
            one.setBirthday(customDetailVo.getBirthday());
        }
        if (!Objects.equals(customDetailVo.getRemark(), one.getRemark())) {
            one.setRemark(customDetailVo.getRemark());
        }
        if (!Objects.equals(customDetailVo.getBlockNotice(), one.getBlockNotice())){
            one.setBlockNotice(customDetailVo.getBlockNotice());
        }
        one.setUPDATED_TIME(new Date());
        if (!update(one, wrapper)) {
            return AjaxResult.error("修改失败");
        }
        return AjaxResult.success("修改成功", one);
    }

    @Override
    public EmpCustomDetail getCustomDetailByCustomID(String customID) {
        //构造条件
        LambdaQueryWrapper<EmpCustomDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EmpCustomDetail::getCustomID, customID);
        return getOne(wrapper);
    }

    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    ISMSService  smsService;
    /**
     * wait
     * 获取验证码
     */
	@Override
	public String wGetVerCode(String phoneNumber) {
		String str = randomCode(); 		
        String key = "verification_code:" + phoneNumber;
        stringRedisTemplate.opsForValue().set(key, str, 300, TimeUnit.SECONDS);		//放入redis
        smsService.sendVerification(phoneNumber, str);
		return "短信已发送";
	}
	
	private String randomCode() {
		String str = "";
		
		Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int randomNumber = random.nextInt(10); // 生成0到9之间的随机数
            str += randomNumber;
        }
		
		return str;
	}

	@Override
	public Result wLogin(EmpCustomDetailVW empCustomDetailVW) {
//		Timer timer = new Timer();
//
//        TimerTask task = new TimerTask() {
//            @Override
//            public void run() {
//                // 在这里编写需要延时执行的任务
//                System.out.println("任务执行");
//                // 关闭定时器
//                timer.cancel();
//            }
//        };

        // 延时1秒后执行任务
        //timer.schedule(task, 3000);
		
		EmpCustomDetail empCustomDetail = empCustomDetailVW.toEmpCustomDetail();
		String code = empCustomDetailVW.getCode();
		 
		String key = "verification_code:" + empCustomDetail.getPhoneNumber();
		String getCode = stringRedisTemplate.opsForValue().get(key);
		
		String userKey = "user:" + empCustomDetailVW.getCustomID();
		String getLogin = stringRedisTemplate.opsForValue().get(userKey);
		
		EmpCustomDetailVo vo = customDetailMapper.getCustomInfo(empCustomDetail.getCustomID());
		
		//如果这个账号在5分钟保存期内，则忽略验证码直接登录
		if(vo == null) {
			//删除已登录状态
			stringRedisTemplate.delete(key);
		}else if("true".equals(getLogin)) {
			getPlayerLoginLog(vo);
			stringRedisTemplate.opsForValue().set(userKey, "true", 24, TimeUnit.HOURS);
			stringRedisTemplate.delete(key);
			return ok("登录成功，以成功续时",vo);
  		}else if(!code.equals(getCode)) {
			return error("验证码过期，请重新获取");
		}
		//验证码只能用一次，一次即弃
		stringRedisTemplate.delete(key);
		
		//先查询是否有用户
        LambdaQueryWrapper<EmpCustomDetail> wrapper = new LambdaQueryWrapper<>();

        List<EmpCustomDetail> customDetails = list(wrapper.eq(EmpCustomDetail::getCustomID, empCustomDetail.getCustomID())
        		.eq(EmpCustomDetail::getPhoneNumber, empCustomDetail.getPhoneNumber()));

        
        //System.out.println("我是梓东");
        if (customDetails.size() <= 0 && vo == null) {
        	
            empCustomDetail.setCoins5G(0L);
            empCustomDetail.setTicket(0);
            String Nickname = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
            empCustomDetail.setNickname( empCustomDetail.getPhoneNumber().substring(0, 3) + "****" + empCustomDetail.getPhoneNumber().substring(7) );
            empCustomDetail.setAvatar("/2024-12-03/img/defaultAvatar.png");
            //设置已登录
            empCustomDetail.setStatus(1);
            //设置未进行过兑换
            empCustomDetail.setFirstExchange(1);
            empCustomDetail.setPhoneNumber(empCustomDetailVW.getPhoneNumber());
            //赋值时间和默认值
            Date date = new Date(System.currentTimeMillis());
            DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = sdf.format(date);
            Timestamp nowTime = Timestamp.valueOf(dateStr);
            empCustomDetail.setCREATED_BY(empCustomDetail.getCustomID());
            empCustomDetail.setCREATED_TIME(nowTime);
            empCustomDetail.setDept_id(empCustomDetail.getDept_id());
            
            wrapper = new LambdaQueryWrapper<>();
        	List<EmpCustomDetail> p_customDetails = list(wrapper
        		    .eq(EmpCustomDetail::getPhoneNumber, empCustomDetail.getPhoneNumber())
        		    .eq(EmpCustomDetail::getDept_id, empCustomDetail.getDept_id()));
            
        	if(p_customDetails.size() > 0) {
        		return error("登陆失败，手机号已注册过。");
        	}
        	
            getPlayerLoginLog(empCustomDetail);
            if (!save(empCustomDetail)) {
                return error("系统错误，注册失败，请联系管理员。");
            }
            
            stringRedisTemplate.opsForValue().set(userKey, "true", 300, TimeUnit.SECONDS);
           
           return ok("登陆成功", empCustomDetail);
        } else{
            vo.setStatus(1);
            String pn = vo.getPhoneNumber();
            if(pn == null || "".equals(pn) || "" == pn || "(NULL)".equals(pn)) {
            	Long deptId = vo.getDept_id();
            	
            	wrapper = new LambdaQueryWrapper<>();
            	List<EmpCustomDetail> p_customDetails = list(wrapper
            		    .eq(EmpCustomDetail::getPhoneNumber, empCustomDetail.getPhoneNumber())
            		    .eq(EmpCustomDetail::getDept_id, deptId));
            	
            	if(p_customDetails.size() > 0) {
            		return error("登陆失败，手机号已注册过。");
            	}
            	
            	vo.setPhoneNumber(empCustomDetail.getPhoneNumber());
            }else {
            	if(!empCustomDetailVW.getPhoneNumber().equals(vo.getPhoneNumber())) {
            		return error("登陆失败，请填写正确手机号。");
            	}
            }
            
            //赋值时间和默认值
            vo.setUpdateBy(empCustomDetail.getCustomID());
            vo.setUpdateTime(new Date());
            if(vo.getDept_id() == null) {
            	vo.setDept_id(empCustomDetail.getDept_id());
            }
            stringRedisTemplate.opsForValue().set(userKey, "true", 300, TimeUnit.SECONDS);
            getPlayerLoginLog(vo);
            if (customDetailMapper.updateById(vo)<=0) {
                return error("登录维持中。");
            }
        }
        return ok("登陆成功",vo);
		
	}
	
	
	
	private void getPlayerLoginLog(Object obj) {
		String className = obj.getClass().toString();
		
		EmpPlayerLoginLog loginLog = new EmpPlayerLoginLog();
		
		Date date = new Date(System.currentTimeMillis());
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(date);
        Timestamp nowTime = Timestamp.valueOf(dateStr);
        
        Long deptId = 0L;
        
		if(className.indexOf("EmpCustomDetailVo") != -1) {
			EmpCustomDetailVo vo = (EmpCustomDetailVo)obj;
			loginLog.setCustomId(vo.getCustomID());
			loginLog.setNickName(vo.getNickname());
			loginLog.setLoginTime(nowTime);
			loginLog.setUserId(null);
			deptId = vo.getDept_id();
			
		}else if(className.indexOf("EmpCustomDetail") != -1) {
			EmpCustomDetail vo = (EmpCustomDetail)obj;
			loginLog.setCustomId(vo.getCustomID());
			loginLog.setNickName(vo.getNickname());
			loginLog.setLoginTime(nowTime);
			loginLog.setUserId(null);
			deptId = vo.getDept_id();
		}
		
		EmpStoreVo svo = new EmpStoreVo();
		svo.setDeptId(deptId);
		List<EmpStoreVo> list = IEmpStoreService.selectEmpStoreListByDeptId(svo);
		Long storeId = list.get(0).getStoreId();
		Integer intStoreId = Math.toIntExact(storeId);
		loginLog.setStoreId(intStoreId);
		loginLog.setDeptId(deptId);
		playerLoginMapper.insertLoginLog(loginLog);
	}

}
